package 算法回顾;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-09-12
 **/

public class JZ12矩阵中的路径 {

    // 上右下左
    private int[][] around = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    // 足迹
    private boolean[][] path;
    private char[][] board;
    private int allLength;
    private int itemLength;
    private String word;

    public boolean exist(char[][] board, String word) {
        this.board = board;
        allLength = board.length;
        itemLength = board[0].length;
        path = new boolean[allLength][itemLength];
        this.word = word;
        for (int i = 0; i < allLength; i++) {
            for (int j = 0; j < itemLength; j++) {
                path[i][j] = true;
                if (board[i][j] == word.charAt(0) && dfs(i, j, 1)) {
                    return true;
                }
                path[i][j] = false;
            }
        }
        return false;
    }

    /**
     * 递归寻找
     * x,y坐标
     * index当前找到第几个字符
     */
    private boolean dfs(int x, int y, int index) {
        if (index == word.length()) {
            return true;
        }

        for (int i = 0; i < 4; i++) {

            int nextX = x + around[i][0];
            int nextY = y + around[i][1];
            if (!enableGo(nextX, nextY)) {
                continue;
            }
            path[nextX][nextY] = true;
            if (board[nextX][nextY] == word.charAt(index)) {
                // 可以继续探索
                if (dfs(nextX, nextY, index + 1)){
                    return true;
                }
            }
            path[nextX][nextY] = false;
        }

        return false;
    }

    /**
     * 这个坐标是否可以前往
     */
    private boolean enableGo(int x, int y) {
        return x >= 0 && x <= allLength - 1 && y >= 0 && y <= itemLength -1 && !path[x][y];
    }

    public static void main(String[] args) {
        JZ12矩阵中的路径 n = new JZ12矩阵中的路径();
        char[][] arr = {{'A','A'}};
        boolean result = n.exist(arr, "AAA");
        System.out.println(result);
    }

}
